package com.atguigu.cloud.controller;

import com.atguigu.cloud.entities.PayDTO;
import com.atguigu.cloud.resp.ResultData;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * ClassName:    OrderController
 * Package:  com.atguigu.cloud.controller
 * Description:
 *
 * @Author: interface
 * @Create: 2025/7/16 - 上午7:02
 * @Version: v1.0
 */
@RestController
public class OrderController {

//    public static final String PaymentSrv_ULR = "http://localhost:8001";
    public static final String PaymentSrv_ULR = "http://cloud-payment-service"; // cloud-payment-service: 服务注册上的微服务名称

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/consumer/pay/add")
    public ResultData addOrder(@RequestBody PayDTO payDTO) {
        return restTemplate.postForObject(PaymentSrv_ULR+"/pay/add", payDTO, ResultData.class);
    }

    @DeleteMapping("/consumer/pay/del/{id}")
    public ResultData delOrder(@PathVariable("id") Integer id) {
        restTemplate.delete(PaymentSrv_ULR+"/pay/del/"+id);
        return ResultData.success("删除成功");
    }

    @PutMapping(value = "/consumer/pay/update")
    public ResultData updateOrder(@RequestBody PayDTO payDTO) {
        restTemplate.put(PaymentSrv_ULR+"/pay/update",payDTO);
        return ResultData.success("修改成功");
    }

    @GetMapping(value = "/consumer/pay/get/{id}")
    public ResultData getPay(@PathVariable("id") Integer id) {
        return restTemplate.getForObject(PaymentSrv_ULR+"/pay/get/"+id, ResultData.class);
    }

    @GetMapping(value = "/consumer/pay/all")
    public ResultData getAllPay() {
        return restTemplate.getForObject(PaymentSrv_ULR+"/pay/all", ResultData.class);
    }

    @GetMapping(value="/consumer/pay/get/info")
    public ResultData<String> getPayDTO(){
        return restTemplate.getForObject(PaymentSrv_ULR+"/pay/get/info", ResultData.class);
    }


    @Resource
    private DiscoveryClient discoveryClient;

    @GetMapping("/consumer/discovery")
    public String discovery(){
        List<String> services = discoveryClient.getServices();
        for (String element : services) {
            System.out.println(element);
        }

        System.out.println("===================================");

        List<ServiceInstance> instances = discoveryClient.getInstances("cloud-payment-service");
        for (ServiceInstance element : instances) {
            System.out.println(element.getServiceId()+"\t"+element.getHost()+"\t"+element.getPort()+"\t"+element.getUri());
        }

        return instances.get(0).getServiceId()+":"+instances.get(0).getPort();
    }
}
